package com.lqq.chapter02.sync;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author lqq677
 * @Date 2021/8/9 10:07
 * @Description 在高内聚低耦合前提下：线程  操作(对外暴露的调用方法)  资源类
 *  3个售票员卖30张票
 */

//第一步 创建资源类，定义属性和操作方法
class Ticket {
    //票数(资源)
    private Integer ticket = 30;
    //操作方法：卖票
    public synchronized void sale() {
            //判断是否有票
        if (ticket > 0) {
            System.out.println(Thread.currentThread().getName() + "卖出" + (ticket--) + "，剩余" + ticket);
        }

    }

}

public class SaleTicket {
    //第二步 创建多个线程，调用资源类的操作方法
    public static void main(String[] args) {

        //创建Ticket对象(资源)
        Ticket ticket = new Ticket();

        //3个(售票员)线程
        new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < 40; i++) {
                            ticket.sale();
                        }
                    }
                }, "AA").start();

        new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < 40; i++) {
                            ticket.sale();
                        }
                    }
                }, "BB").start();

        new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < 40; i++) {
                            ticket.sale();
                        }
                    }
                }, "CC").start();
    }
}
